'''
Created on Jan 17, 2011

@author: Administrator
'''
import unittest


import mock
from mock import patch, Mock

from testutil import *
stub_symbian()

from sniffylib.rpc import core
from sniffylib.rpc import socketsms
from sniffylib.rpc import shell

PASSWORD = 'password'
BAD_PASSWORD = ''
USER = 'marek'

def own(svc, user, password):
        OWN_CMD = 'own %s' % password
        svc.handle(OWN_CMD, user)


class Test(BaseTest):


    @patch('smswatch.SMSEngine', create=True)
    def setUp(self, LocationService):
        self.sh = shell.SniffyShell(PASSWORD, {})
        self.msg_svc = socketsms.SmsSocketService(self.sh)

    def tearDown(self):
        pass


    def testHandleOwn(self):
        msvc = self.msg_svc
        res_handler = Mock()
        msvc.result_handler = res_handler
        own(msvc, USER, PASSWORD)
        self.assertEquals(USER, self.sh.master.name)
        res_handler.handle_result.assert_called_with(self.sh, core.MSG_OK_TEMPL % 'own')
        

    def testHandleWithErrorDesired(self):
        msvc = self.msg_svc
        res_handler = Mock()
        error_handler = Mock()
        msvc.result_handler = res_handler
        msvc.error_handler = error_handler
        own(msvc, USER, PASSWORD)
        self.assertEquals(USER, self.sh.master.name)
        res_handler.handle_result.assert_called_with(self.sh, core.MSG_OK_TEMPL % 'own')
        res_handler.reset_mock()
        msvc.handle('loc', USER)
        self.assertNotCalled(res_handler.handle_result)
        error_handler.handle_error.assert_called_with(self.sh, core.MSG_ERROR_TEMPL % ('loc', core.MSG_UNDEFINED_ERROR))

    def testHandleBadCommandWithErrorDesired(self):
        msvc = self.msg_svc
        res_handler = Mock()
        error_handler = Mock()
        msvc.result_handler = res_handler
        msvc.error_handler = error_handler
        own(msvc, USER, PASSWORD)
        self.assertEquals(USER, self.sh.master.name)
        res_handler.handle_result.assert_called_with(self.sh, core.MSG_OK_TEMPL % 'own')
        res_handler.reset_mock()
        msvc.handle('non', USER)
        self.assertNotCalled(res_handler.handle_result)
        error_handler.handle_error.assert_called_with(self.sh, core.MSG_ERROR_TEMPL % ('non', core.MSG_BAD_CMD_ERROR))


    def testHandleWithErrorUndesired(self):
        msvc = self.msg_svc
        res_handler = Mock()
        error_handler = Mock()
        msvc.result_handler = res_handler
        msvc.error_handler = error_handler
        own(msvc, USER, BAD_PASSWORD)
        self.assertNotEquals(USER, self.sh.master)
        self.assertNotCalled(error_handler.handle_error)
        self.assertNotCalled(res_handler.handle_result)
        

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()